<html>
<head>
  <script src="../../lib/OpenLayers.js"></script>
  <script type="text/javascript">

    function test_initialize(t) {
        t.plan(3);

        var protocol = new OpenLayers.Protocol.CSW({formatOptions: {foo: "bar"}});
        t.ok(protocol instanceof OpenLayers.Protocol.CSW.v2_0_2,
             "initialize returns instance of default versioned protocol");
        var format = protocol.format;
        t.ok(format instanceof OpenLayers.Format.CSWGetRecords.v2_0_2, "Default format created");
        t.ok(format.foo, "bar", "formatOptions set correctly");
        protocol.destroy();
    }

    function test_read(t) {
        t.plan(6);

        var protocol = new OpenLayers.Protocol.CSW({
            url: "http://some.url.org",
            parseData: function(request) {
                t.eq(request.responseText, "foo", "parseData called properly");
                return "foo";
            }
        });

        var _POST = OpenLayers.Request.POST;

        var expected, status;
        OpenLayers.Request.POST = function(obj) {
            t.xml_eq(new OpenLayers.Format.XML().read(obj.data).documentElement, expected, "GetRecords request is correct");
            obj.status = status;
            obj.responseText = "foo";
            obj.options = {};
            t.delay_call(0.1, function() {obj.callback.call(this)});
            return obj;
        };

        expected = readXML("GetRecords");
        status = 200;
        var data = {
            "resultType": "results",
            "maxRecords": 100,
            "Query": {
                "typeNames": "gmd:MD_Metadata",
                "ElementSetName": {
                    "value": "full"
                }
            }
        };
        var response = protocol.read({
            params: data,
            callback: function(response) {
                t.eq(response.data, "foo", "user callback properly called with data");
                t.eq(response.code, OpenLayers.Protocol.Response.SUCCESS, "success reported properly to user callback");
            }
        });

        var options = {
            params: data,
            callback: function(response) {
                t.eq(response.code, OpenLayers.Protocol.Response.FAILURE, "failure reported properly to user callback");
            }
        };
        status = 400;
        var response = protocol.read(options);

        OpenLayers.Request.POST = _POST;
    }

    function readXML(id) {
        var xml = document.getElementById(id).firstChild.nodeValue;
        return new OpenLayers.Format.XML().read(xml).documentElement;
    }

  </script>
</head>
<body>
<div id="map" style="width:512px; height:256px"> </div>
<div id="GetRecords"><!--
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" service="CSW" version="2.0.2" resultType="results" maxRecords="100">
  <csw:Query typeNames="gmd:MD_Metadata">
    <csw:ElementSetName>full</csw:ElementSetName>
  </csw:Query>
</csw:GetRecords>
--></div>
</body>
</html>
